<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>课程管理</el-breadcrumb-item>
    <el-breadcrumb-item>课程视频管理</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 搜索区域 -->
  <div class="search-bar">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="视频名称:">
        <el-input
            v-model="formInline.videoName"
            placeholder="请输入视频名称"
            clearable
            :suffix-icon="Search"
            @clear="handleClear"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button type="primary" @click="openAddDialog">新增视频</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 视频列表表格 -->
  <el-table
      :data="tableData"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" fixed width="50" />
    <el-table-column prop="id" label="视频id" width="80" />
    <el-table-column prop="videoName" label="视频名称" width="200" />
    <el-table-column prop="videoView" label="视频预览" width="300">
      <template #default="scope">
        <video
            :src="'http://localhost:8080' + scope.row.videoUrl"
            alt="视频预览"
            style="
            width: 100px;
            height: 100px;
            line-height: 100px;
            border: 1px;
            background-color: #f5f7fa;
            cursor: pointer;
          "
            @click="previewVideo(scope.row)"
        ></video>
      </template>
    </el-table-column>
    <el-table-column prop="videoTime" label="视频时长" width="160" />
    <el-table-column
        prop="course.courseName"
        label="所属课程"
        width="160"
    />
    <el-table-column fixed="right" label="操作" min-width="150">
      <template #default="scope">
        <el-button
            type="primary"
            size="small"
            @click="previewVideo(scope.row)"
        >预览</el-button
        >
        <el-button
            type="warning"
            size="small"
            @click="editVideo(scope.row)"
        >编辑</el-button
        >
        <el-button
            type="danger"
            size="small"
            @click="removeVideo(scope.row.id)"
        >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!-- 新增视频弹窗 -->
  <el-dialog
      v-model="addDialogVisible"
      title="新增课程视频"
      width="500"
      @close="handleAddDialogClose"
  >
    <el-form :label-width="formLabelWidth" label-align="right">
      <el-form-item label="视频名称">
        <el-input
            v-model="addForm.videoName"
            autocomplete="off"
            placeholder="请输入视频名称（最多50字）"
            :maxlength="50"
            show-word-limit
        />
      </el-form-item>
      <el-form-item label="视频上传">
        <el-upload
            action="http://localhost:8080/upload"
            list-type="text"
            :on-success="handleAddUploadSuccess"
            :on-exceed="handleExceed"
            :limit="1"
            :file-list="addFileList"
            :on-remove="handleAddRemove"
            :before-upload="beforeVideoUpload"
        >
          <el-icon
              style="
              width: 128px;
              height: 128px;
              border: 1px dashed #dcdfe6;
              border-radius: 5px;
              font-size: 20px;
            "
          >
            <Plus />
          </el-icon>
        </el-upload>
        <div class="text-tip">仅支持上传视频格式文件（如 mp4、avi 等）</div>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="预览图片" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="所属课程">
        <el-select
            v-model="addForm.courseId"
            placeholder="请选择课程"
            style="width: 100%"
            clearable
        >
          <el-option
              v-for="item in courses"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 编辑视频弹窗 -->
  <el-dialog
      v-model="editDialogVisible"
      title="编辑课程视频"
      width="500"
      @close="handleEditDialogClose"
  >
    <el-form :label-width="formLabelWidth" label-align="right">
      <el-form-item label="视频名称">
        <el-input
            v-model="editForm.videoName"
            autocomplete="off"
            placeholder="请输入视频名称（最多50字）"
            :maxlength="50"
            show-word-limit
        />
      </el-form-item>
      <el-form-item label="修改视频">
        <div>
          <div v-if="editForm.videoUrl" style="margin-bottom: 10px;">
            <el-button
                type="primary"
                size="small"
                @click="previewVideo(editForm)"
            >预览现有视频</el-button
            >
          </div>
          <el-upload
              action="http://localhost:8080/upload"
              list-type="text"
              :on-success="handleEditUploadSuccess"
              :on-exceed="handleExceed"
              :limit="1"
              :file-list="editFileList"
              :on-remove="handleEditRemove"
              :before-upload="beforeVideoUpload"
          >
            <el-icon
                style="
                width: 128px;
                height: 128px;
                border: 1px dashed #dcdfe6;
                border-radius: 5px;
                font-size: 20px;
              "
            >
              <Plus />
            </el-icon>
          </el-upload>
          <div class="text-tip">仅支持上传视频格式文件（如 mp4、avi 等）</div>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="预览图片" />
          </el-dialog>
        </div>
      </el-form-item>
      <el-form-item label="所属课程">
        <el-select
            v-model="editForm.courseId"
            placeholder="请选择课程"
            style="width: 100%"
            clearable
        >
          <el-option
              v-for="item in courses"
              :key="item.id"
              :label="item.courseName"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 视频预览弹窗 -->
  <el-dialog
      v-model="videoPreviewVisible"
      title="视频预览"
      width="80%"
      :before-close="handleVideoClose"
  >
    <div style="display: flex; justify-content: center; padding: 20px 0;">
      <video
          :src="'http://localhost:8080' + currentVideoUrl"
          controls
          style="max-width: 100%; max-height: 600px;"
          @error="handleVideoError"
      >
        您的浏览器不支持HTML5视频播放
      </video>
    </div>
    <template #footer>
      <el-button @click="videoPreviewVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 常量定义
const MAX_VIDEO_NAME_LENGTH = 50 // 视频名称最大长度
const VIDEO_TYPES = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv'] // 支持的视频格式

// 响应式数据 - 搜索表单
const formInline = reactive({
  videoName: ''
})

// 响应式数据 - 表格&分页
const tableData = ref([])
const selectedRows = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

// 响应式数据 - 弹窗（新增、编辑、预览）
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const videoPreviewVisible = ref(false)
const dialogVisible = ref(false)
const formLabelWidth = '120px'

// 响应式数据 - 新增弹窗表单
const addForm = reactive({
  videoName: '',
  videoUrl: '',
  courseId: ''
})
const addFileList = ref([])

// 响应式数据 - 编辑弹窗表单
const editForm = reactive({
  id: '',
  videoName: '',
  videoUrl: '',
  courseId: ''
})
const editFileList = ref([])

// 响应式数据 - 课程下拉选项
const courses = ref([])

// 响应式数据 - 视频预览
const currentVideoUrl = ref('')
const dialogImageUrl = ref('')

// ============== 生命周期 ==============
onMounted(() => {
  fetchCourses() // 获取课程列表
  fetchVideoList() // 获取视频列表
})

// ============== 方法 - 数据请求 ==============
/**
 * 获取课程列表（用于下拉选择）
 */
const fetchCourses = () => {
  axios
      .get('http://localhost:8080/course')
      .then((res) => {
        courses.value = res.data.data || []
      })
      .catch((err) => {
        console.error('获取课程列表失败:', err)
        ElMessage.error('获取课程列表失败，请稍后重试')
      })
}

/**
 * 获取视频列表（表格渲染）
 */
const fetchVideoList = () => {
  const params = {
    pageSize: pageSize.value,
    pageNum: currentPage.value,
    videoName: formInline.videoName || undefined
  }
  // 清理空参数
  Object.keys(params).forEach((key) => {
    if (params[key] === undefined || params[key] === '') {
      delete params[key]
    }
  })
  axios
      .get('http://localhost:8080/courseVideo/page', { params })
      .then((res) => {
        tableData.value = res.data.data.list || []
        total.value = res.data.data.total || 0
      })
      .catch((err) => {
        console.error('获取视频列表失败:', err)
        ElMessage.error('获取视频列表失败，请稍后重试')
      })
}

// ============== 方法 - 搜索&分页 ==============
/**
 * 搜索提交
 */
const onSubmit = () => {
  currentPage.value = 1 // 搜索时重置页码
  fetchVideoList()
}

/**
 * 清除搜索条件
 */
const handleClear = () => {
  formInline.videoName = ''
  currentPage.value = 1
  fetchVideoList()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchVideoList()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchVideoList()
}

// ============== 方法 - 表格操作（删除、多选） ==============
/**
 * 多选事件（用于批量删除）
 */
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

/**
 * 批量删除
 */
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessageBox.alert('至少选择一条数据才能删除', '提示', {
      confirmButtonText: '确定'
    })
    return
  }
  const ids = selectedRows.value.map((row) => row.id).join(',')
  ElMessageBox.confirm('确定删除选中的 ' + selectedRows.value.length + ' 条数据？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios
        .delete(`http://localhost:8080/courseVideo?ids=${ids}`)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success('删除成功')
            fetchVideoList() // 重新获取列表
          } else {
            ElMessage.error('删除失败：' + (res.data.message || '未知错误'))
          }
        })
        .catch((err) => {
          console.error('批量删除失败:', err)
          ElMessage.error('删除操作失败，请稍后重试')
        })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

/**
 * 单个删除
 */
const removeVideo = (id) => {
  ElMessageBox.confirm('确定删除这条数据？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios
        .delete(`http://localhost:8080/courseVideo/${id}`)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success('删除成功')
            fetchVideoList() // 重新获取列表
          } else {
            ElMessage.error('删除失败：' + (res.data.message || '未知错误'))
          }
        })
        .catch((err) => {
          console.error('单个删除失败:', err)
          ElMessage.error('删除操作失败，请稍后重试')
        })
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// ============== 方法 - 弹窗（新增、编辑、预览） ==============
/**
 * 打开新增弹窗
 */
const openAddDialog = () => {
  addDialogVisible.value = true
  // 重置表单
  addForm.videoName = ''
  addForm.videoUrl = ''
  addForm.courseId = ''
  addFileList.value = []
}

/**
 * 关闭新增弹窗（重置状态）
 */
const handleAddDialogClose = () => {
  addFileList.value = []
}

/**
 * 确认新增
 */
const confirmAdd = () => {
  if (!addForm.videoName) {
    ElMessage.warning('请输入视频名称')
    return
  }
  if (!addForm.videoUrl) {
    ElMessage.warning('请上传视频文件')
    return
  }
  if (!addForm.courseId) {
    ElMessage.warning('请选择所属课程')
    return
  }

  // 确保视频名称不超过最大长度
  if (addForm.videoName.length > MAX_VIDEO_NAME_LENGTH) {
    addForm.videoName = addForm.videoName.substring(0, MAX_VIDEO_NAME_LENGTH)
  }

  axios
      .post('http://localhost:8080/courseVideo', {
        videoName: addForm.videoName,
        videoUrl: addForm.videoUrl,
        courseId: addForm.courseId
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('新增成功')
          addDialogVisible.value = false
          fetchVideoList() // 重新获取列表
        } else {
          ElMessage.error('新增失败：' + (res.data.message || '未知错误'))
        }
      })
      .catch((err) => {
        console.error('新增视频失败:', err)
        ElMessage.error('新增操作失败，请稍后重试')
      })
}

/**
 * 打开编辑弹窗
 */
const editVideo = (row) => {
  editDialogVisible.value = true
  // 复制行数据到编辑表单
  editForm.id = row.id
  editForm.videoName = row.videoName || ''
  editForm.videoUrl = row.videoUrl || ''
  editForm.courseId = row.courseId || ''

  // 初始化文件列表
  if (row.videoUrl) {
    editFileList.value = [
      {
        url: 'http://localhost:8080' + row.videoUrl,
        name: truncateFileName(row.videoName || '视频文件'),
        status: 'success'
      }
    ]
  } else {
    editFileList.value = []
  }
}

/**
 * 关闭编辑弹窗（重置状态）
 */
const handleEditDialogClose = () => {
  editFileList.value = []
}

/**
 * 确认编辑
 */
const confirmEdit = () => {
  if (!editForm.videoName) {
    ElMessage.warning('请输入视频名称')
    return
  }
  if (!editForm.courseId) {
    ElMessage.warning('请选择所属课程')
    return
  }

  // 确保视频名称不超过最大长度
  if (editForm.videoName.length > MAX_VIDEO_NAME_LENGTH) {
    editForm.videoName = editForm.videoName.substring(0, MAX_VIDEO_NAME_LENGTH)
  }

  axios
      .put('http://localhost:8080/courseVideo', {
        id: editForm.id,
        videoName: editForm.videoName,
        videoUrl: editForm.videoUrl,
        courseId: editForm.courseId
      })
      .then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('编辑成功')
          editDialogVisible.value = false
          fetchVideoList() // 重新获取列表
        } else {
          ElMessage.error('编辑失败：' + (res.data.message || '未知错误'))
        }
      })
      .catch((err) => {
        console.error('编辑视频失败:', err)
        ElMessage.error('编辑操作失败，请稍后重试')
      })
}

/**
 * 预览视频
 */
const previewVideo = (row) => {
  if (!row.videoUrl) {
    ElMessage.warning('该视频暂无预览链接')
    return
  }
  currentVideoUrl.value = row.videoUrl
  videoPreviewVisible.value = true
}

/**
 * 关闭视频预览前处理
 */
const handleVideoClose = (done) => {
  const videoEl = document.querySelector('video')
  if (videoEl) {
    videoEl.pause() // 暂停视频播放
  }
  done()
}

/**
 * 视频加载错误处理
 */
const handleVideoError = () => {
  ElMessage.error('视频加载失败，请检查视频链接或格式')
}

// ============== 方法 - 文件上传相关 ==============
/**
 * 视频上传前校验
 */
const beforeVideoUpload = (file) => {
  const isVideo = VIDEO_TYPES.includes(file.type)
  if (!isVideo) {
    ElMessage.error('只能上传视频文件（支持 mp4、avi、mov、wmv 格式）')
    return false
  }
  return true
}

/**
 * 处理文件超出限制（替换功能）
 */
const handleExceed = (files, fileList) => {
  // 保留最新的一个文件
  const newFile = files[0]
  const truncatedName = truncateFileName(newFile.name)

  if (addDialogVisible.value) {
    addFileList.value = [{ ...newFile, name: truncatedName }]
  } else {
    editFileList.value = [{ ...newFile, name: truncatedName }]
  }

  ElMessage.warning('只能上传一个视频文件，已自动替换为新文件')
}

/**
 * 新增视频上传成功处理
 */
const handleAddUploadSuccess = (res, file) => {
  addForm.videoUrl = res.data
  addFileList.value = [
    {
      url: 'http://localhost:8080' + res.data,
      name: truncateFileName(file.name),
      status: 'success'
    }
  ]
}

/**
 * 编辑视频上传成功处理
 */
const handleEditUploadSuccess = (res, file) => {
  editForm.videoUrl = res.data
  editFileList.value = [
    {
      url: 'http://localhost:8080' + res.data,
      name: truncateFileName(file.name),
      status: 'success'
    }
  ]
}

/**
 * 新增视频移除处理
 */
const handleAddRemove = () => {
  addForm.videoUrl = ''
}

/**
 * 编辑视频移除处理
 */
const handleEditRemove = () => {
  editForm.videoUrl = ''
}

/**
 * 图片预览处理
 */
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

/**
 * 截断文件名（显示长度限制）
 */
const truncateFileName = (name) => {
  const maxLength = 30
  if (!name || name.length <= maxLength) return name

  const lastDotIndex = name.lastIndexOf('.')
  if (lastDotIndex > 0) {
    const ext = name.substring(lastDotIndex)
    const baseName = name.substring(0, lastDotIndex)
    if (baseName.length > maxLength - ext.length) {
      return baseName.substring(0, maxLength - ext.length - 3) + '...' + ext
    }
  }

  return name.substring(0, maxLength - 3) + '...'
}
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.text-tip {
  font-size: 12px;
  color: #8c8c8c;
  margin-top: 5px;
}

::v-deep .el-upload-list__item {
  max-width: 350px;
}

::v-deep .el-breadcrumb {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

::v-deep .el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
